<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SendNotifyAll extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SendNotifyAll';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '官方全员推送';
    protected $apiCon = 'api';
    protected $log = 'officeSendNotify'; //日志
    protected $table = 'send_alluser_notify';//全员推送通知表
    protected $logtable = 'send_alluser_notify_log';//
    protected $usertable = 'user';//用户表

    protected $finance_recharge_order_table = 'finance_recharge_order';//订单充值表

    protected $errorLog = 'error_send_alluser_notify'; //错误日志
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        set_time_limit(0);
        //获取满足条件的数据
        $count = DB::connection($this->apiCon)->table($this->table)->where("send_time", strtotime(date('Y-m-d H:i', time())))->where(['send_status'=>0,'is_delete'=>0])->count();
        if ($count == 0) {
            write_log($this->log, "当前暂无发送队列", '');
        } else {
            //计算页数
            $nums = 1000;//一次多少条
            $page = ceil($count / $nums);
            for ($i = 0; $i < $page; $i++) {
                //偏移量
                $limitset = (($i + 1) - 1) * $nums;
                //获取分页数据
                $datas = DB::connection($this->apiCon)->table($this->table)
                ->where("send_time", strtotime(date('Y-m-d H:i', time())))
                ->where(['send_status'=>0,'is_delete'=>0])
                ->offset($limitset)
                ->limit($nums)
                ->get();
                $datas = objToArray($datas);
                foreach ($datas as $v) {
                    try {
                        //若非全员时候查询用户是否满足最小金额和最大金额限制
                        $newUserIds = []; //消息推送使用userid 
                        $failUserids = []; // 失败数组UUID
                        $uuidArr = [];//要推送的UUID数组
                        if($v['is_all']==0)
                        {
                            //查询用户数据是否满足最大最小金额若满足则添加进去
                            $userids = explode(',',$v['userids']);
                            foreach($userids as $val)
                            {
                                //uuid转userID
                                $userinfo = DB::connection($this->apiCon)->table($this->usertable)->where('uuid',$val)->first(['user_id']);
                                $userinfo = objToArray($userinfo);
                                //查询用户充值情况
                                $userRecharge = DB::connection($this->apiCon)->table($this->finance_recharge_order_table)
                                ->where('user_id', $userinfo['user_id'])
                                ->where('status', 1)
                                ->sum("price");
                                if (!empty($userRecharge))
                                {
                                    //转换为钻石数
                                    $userRecharge = $userRecharge/10;
                                }
                                if($userRecharge >= $v['min_damion'] && $userRecharge <= $v['max_damion'])
                                {
                                    $newUserIds[]= $userinfo['user_id']; 
                                    $uuidArr[] = $val;
                                }else{
                                    $failUserids[] = $val;
                                }
                            }
                            //记录失败发送记录
                            if(!empty($failUserids))
                            {
                                //不符合最大钻石,最小限制用户记录
                                $insert['notifyid']= $v['id'];
                                $insert['userid'] = implode(',',$failUserids);
                                $insert['status'] = 2;//失败
                                $insert['note'] = '未满足最大最小钻石限制';
                                $insert['create_time'] = Carbon::now()->toDateTimeString();

                                DB::connection($this->apiCon)->table($this->logtable)->insert($insert);
                            }
                            
                        }
                        //调用发送官方消息接口
                        $data['is_all'] = $v['is_all'];//全员状态1全员0非全员
                        $data['userids'] = $newUserIds;//用户id
                        $data['send_type'] = $v['send_type'];//1图文0文案
                        $data['send_content'] = $v['send_content'];//发送文案
                        $data['title'] = $v['title'];//图文标题
                        $data['img_url'] = $v['img_url'];//图片地址
                        $data['action_url'] = $v['action_url'];//图文跳转链接
                        $data['notify_type'] = $v['notify_type'];//推送类型1=官方消息 2=游戏推送
                        $data['notify_id'] = $v['id'];
                        $status = curl_request(getKkaudioApiUrl() . '/inner/officenotify/brocast', $data, 'json', 'POST');
                    } catch (\Exception $e) {
                        write_log($this->errorLog, "发送信息入库失败", $e->getMessage());
                    }
                }
            }
        }
    }
}
